import { zodToJsonSchema } from "zod-to-json-schema";
import { logger } from '../tools/index.js';
export const createPlugin = plugin => {
    const requestSchemaJson = zodToJsonSchema(plugin.requestSchema);
    const params = Object.keys(requestSchemaJson?.properties || {}).map(propKey => {
        const propObj = requestSchemaJson.properties[propKey];
        return { name: propKey, type: propObj.type, description: propObj.description, required: (requestSchemaJson.required || []).includes(propKey) }
    });
    const executePlugin = async (plugin, pluginArg, context) => {
        try {
            logger.info(`execute plugin %s, args = %s`, plugin.name, JSON.stringify(pluginArg));
            const pluginArgObj = await plugin.requestSchema.parseAsync(pluginArg);
            const res = await plugin.func(pluginArgObj, context);
            return res || '执行成功';
        } catch (err) {
            logger.error(`execute plugin %s, args = %s`, plugin.name, JSON.stringify(pluginArg), err);
            return `执行失败，错误信息：${err}`;
        }
    }
    return {
        ...plugin,
        params,
        func: async (...args) => {
            const pluginParamList = args[0];
            const context = args[1];
            const respList = [];
            if (pluginParamList && pluginParamList.length > 0) {
                for (const pluginArg of pluginParamList) {
                    const pluginRes = await executePlugin(plugin, pluginArg, context);
                    respList.push(pluginRes);
                }
            } else {
                const pluginRes = await executePlugin(plugin, null, context);
                respList.push(pluginRes);
            }
            return respList;
        },
    }
}

export const createPlugins = plugins => plugins.map(createPlugin);